<template>
	<view>
		<view class="myhome">
			<!-- 已登录 -->
			<view class="wx-name" v-if="wxlogin">
				<view><image :src="user.avatarUrl"></image></view>
				<view class="wx-text">
					<text>{{user.nickName}}</text>
				</view>
			</view>

			<!-- 未登录 -->
			<view class="wx-button" v-if="!wxlogin">
				<view class="wx-button-view">登录美团外卖，开启吃货旅程</view>
				<view><button plain="true" open-type="getUserInfo" @getuserinfo="getUserInfo">去登录</button></view>
			</view>
		</view>
	</view>
</template>

<script>
	// 拿到地址
	import {loginurl} from "../../api/request.js"
	// 拿到POST方法
	import {publicing} from "../../api/api.js"
	export default{
		data() {
			return {
				wxlogin: true,
				user:{}
			}
		},
		methods:{
			// 弹出授权框，获取头像和昵称
			getUserInfo(e){
				console.log(e)
				if(e.detail.userInfo){
					let avatarUrl=e.detail.userInfo.avatarUrl
					let nickName=e.detail.userInfo.nickName
					this.getcode(avatarUrl,nickName)
				}
			},
			// 获取code 
			getcode(avatarUrl,nickName){
				uni.login({
					success: (res)=>{
					    console.log(res);
						let code=res.code
						this.getlogin(avatarUrl,nickName,code)
					  },
					fail: (err)=>{
						console.log(err)
					}
				})
			},
			// 登录，获取openid
			getlogin(avatarUrl,nickName,code){
				let data={
					avatarUrl,
					nickName,
					code,
					appid:"wxe390de17ed120ed4",
					secret:"c7a13b25635f52db384c98bb98f4f206"
				}
				publicing(loginurl,data)
				.then(res=>{
					console.log(res)
					// 将得到的openid存到本地，方便以后使用
					if(res.data.msg=="success"){
						// 存入本地
						uni.setStorageSync("username",res.data.datas)
						this.getusermaninfo()
					}
				})
				.catch(err=>{
					console.log(err)
				})
			},
			// 取出本地存入的数据（万一用户不是从我的页面登录的，也可以从本地取出数据）
			getusermaninfo(){
				let data=uni.getStorageSync("username")
				console.log(data)
				if(!data){
					console.log("用户没有登录或登录已过期")
					this.wxlogin=false
				}else{
					console.log("用户登录")
					this.wxlogin=true
					this.user=data
				}
			}
		},
		onShow() {
			// onshow是每次跳到这个页面都执行一次
			this.getusermaninfo()
		}
	}
</script>

<style scoped>
.myhome {
	background: linear-gradient(to top, #ffe566 10%, #ffd300 100%);
	height: 350upx;
	display: flex;
	align-items: center;
}
.wx-name image {
	width: 120upx !important;
	height: 120upx !important;
	border-radius: 50%;
	margin-right: 20upx;
	border: 10rpx solid #999999;
}
text {
	display: block;
	margin: 10upx 0;
	color: #999999;
}
.wx-name {
	display: flex;
	align-items: center;
	padding: 0 30upx;
	align-content: center;
	height: 200upx;
}
.wx-text text {
	font-size: 35upx;
}
/* 登录 */
.wx-button button {
	border: none;
	font-size: 30upx;
	background: linear-gradient(to right, #28a6f1 10%, #0e8dd7 80%);
	border-radius: 50upx;
	color: #ffffff;
}
.wx-button-view {
	font-size: 35upx;
	color: #ffffff;
	margin-bottom: 25upx;
}
.wx-button {
	margin: 0 auto;
}
</style>
